package com.systop.asset.controller;


import com.systop.asset.entity.RestResponse;
import com.systop.asset.enums.HttpCodeEnum;
import com.systop.asset.exception.SystemException;
import com.systop.asset.utils.PathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${upload.path}")
    private String path;

    @Value("${upload.profile}")
    private String profile;

    @Value("${upload.fileType}")
    private String[] fileType;


    /**
     * 通用上传请求（单个）
     */

    @PostMapping("/upload")
    public RestResponse uploadFile(@RequestPart("file")MultipartFile file)
    {
        try{
            System.out.println("文件拷贝开始");
            boolean flag = false;
            for(String type : fileType)
                //判断文件类型
                if(file.getOriginalFilename().endsWith(type))
                    flag = true;
            if(!flag) throw new SystemException(HttpCodeEnum.FILE_TYPE_ERROR);
            String imgPath = PathUtils.imgPath(path,file.getOriginalFilename());
            Path uploadPath = Paths.get(path + "/"+ imgPath);
            file.transferTo(uploadPath.toFile());
            System.out.println("文件拷贝成功");
            return RestResponse.success(profile + "/" + imgPath);
        } catch (IOException e) {
                System.err.println("文件拷贝失败: " + e.getMessage());
            return RestResponse.failure(400,"文件上传失败");
        }
    }


    @PostMapping("/uploads")
    public RestResponse uploadFiles(@RequestPart("files") List<MultipartFile> files){

        try{
            List<String> urls = new ArrayList<>();
            //判断文件类型
            for(MultipartFile file : files){
                boolean flag = false;
                for(String type : fileType)
                    //判断文件类型
                    if(file.getOriginalFilename().endsWith(type))
                        flag = true;
                if(!flag) throw new SystemException(HttpCodeEnum.FILE_TYPE_ERROR);
                String imgPath = PathUtils.imgPath(path,file.getOriginalFilename());

                Path uploadPath = Paths.get(path + "/"+ imgPath);
                file.transferTo(uploadPath.toFile());
                urls.add(profile + "/" + imgPath);
                System.out.println("文件拷贝成功");
            }
            return RestResponse.success(urls);
        } catch (IOException e) {
                System.err.println("文件拷贝失败: " + e.getMessage());
            return RestResponse.failure(400,"文件上传失败");
        }
    }


    /**
     * 获取服务器URL
     */
    private String getServerUrl() {
        // 这里可以根据实际情况调整服务器URL
        return "http://localhost:8080";
    }




    // 文件类型校验
    public void fileVerification(MultipartFile file) throws IOException {
        // 文件大小检查
        if (file.getSize() > 10 * 1024 * 1024) { // 最大10MB

            throw new SystemException(HttpCodeEnum.FILE_SIZE_EXCEED_LIMIT);
        }

        // 文件类型检查
        String contentType = file.getContentType();
        List<String> allowedTypes = Arrays.asList("image/jpeg", "image/png", "image/gif","application/pdf");
        if (!allowedTypes.contains(contentType)) {
            throw new SystemException(HttpCodeEnum.INVALID_FILE_TYPE);
        }

        // 文件名检查
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !(originalFilename.endsWith(".jpg") || originalFilename.endsWith(".png") || originalFilename.endsWith(".gif")||originalFilename.endsWith(".pdf"))) {
            throw new SystemException(HttpCodeEnum.ILLEGAL_FILENAME);
        }

        // MIME类型检查
        String actualFileType = Files.probeContentType(Paths.get(file.getOriginalFilename()));
        if (!allowedTypes.contains(actualFileType)) {
            throw new SystemException(HttpCodeEnum.FILE_MIME_TYPE_MISMATCH);
        }
    }

}
